//
//  LawMetrailTableVC.m
//  Cunli
//
//  Created by lilubin on 15/7/6.
//  Copyright (c) 2015年 lilubin. All rights reserved.
//

#import "LawMetrailTableVC.h"
#import "MyDataService.h"
#import "NSString+MD5.h"
#import "LearnModel.h"
#import "LearnCell.h"
#import "UIImageView+WebCache.h"
#import "MJRefresh.h"
#import "Config.h"
#import "MBProgressHUD.h"
#import "SwipableViewController.h"
#import "ChildMetrailVC.h"
#import "MediaDetailVC.h"
#import "BookDetailVC.h"
#import "LBBtnModel.h"
#import "ChildLearnBtn.h"
#import "UIColor+expanded.h"

#define kScreenWidth [UIScreen mainScreen].bounds.size.width
#define pageSize 6

static NSString *kLearnCellID = @"LearnCell";


@interface LawMetrailTableVC ()
{
    NSMutableArray *_datasArray; //存放消息模型的数组
}

@property (nonatomic, strong) SwipableViewController *childSwipableVC;
@end

@implementation LawMetrailTableVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.tableView.rowHeight = 90;
    [self reloadDataToNew:YES];
    [self registerNewsCell];
    [self addRefreshAttribute];
    self.tableView.separatorColor = [UIColor colorWithHexString:TableViewSeperateColorValue];
    if (_lawType == LearnTableViewMetrail) {
        [self initAllAttributes];
        [self createHeaderView];
    }
}

- (void)initGlobalParams
{
    _datasArray = [NSMutableArray arrayWithCapacity:6];
}

- (void)initAllAttributes
{
    ChildMetrailVC *childVCBook = [[ChildMetrailVC alloc] initWithChildLearnType:ChildLearnTypeBook];
    ChildMetrailVC *childVCVideo = [[ChildMetrailVC alloc] initWithChildLearnType:ChildLearnTypeVideo];
    ChildMetrailVC *childVCVoice = [[ChildMetrailVC alloc] initWithChildLearnType:ChildLearnTypeVoice];
    
    NSMutableArray *childVCS = [NSMutableArray arrayWithObjects:childVCBook, childVCVideo, childVCVoice, nil];
    _childSwipableVC = [[SwipableViewController alloc] initWithTitle:@"普法教材" andSubTitles:@[@"图书", @"视频", @"音频"] andControllers:childVCS underTabbar:NO];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

- (void)addRefreshAttribute
{
    __weak typeof(self) weakSelf = self;
    
    [self.tableView addLegendHeaderWithRefreshingBlock:^{
        [weakSelf reloadDataToNew:YES]; //刷新
    }];
    
    [self.tableView addLegendFooterWithRefreshingBlock:^{
        [weakSelf reloadDataToNew:NO]; //加载更多
    }];
}

//注册tableViewCell
- (void)registerNewsCell
{
    UINib *nib = [UINib nibWithNibName:@"LearnCell" bundle:nil];
    [self.tableView registerNib:nib forCellReuseIdentifier:kLearnCellID];
}

//初始化该控制器
- (instancetype)initWithLearnTableListType:(LearnTableViewType)type
{
    self = [super init];
    if (self) {
        _lawType = type;
        [self initGlobalParams];
    }
    return self;
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _datasArray.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    LearnCell *cell = [tableView dequeueReusableCellWithIdentifier:kLearnCellID forIndexPath:indexPath];
    
    if (cell == nil) {
         cell = [[NSBundle mainBundle] loadNibNamed:@"LearnCell" owner:self options:nil].lastObject;
    }
    else
    {
        for(UIView *view in cell.contentView.subviews)
        {
            if (view.tag == 1020) {
                [view removeFromSuperview];
            }
        }
    }

//    LearnCell *cell = [[NSBundle mainBundle] loadNibNamed:@"LearnCell" owner:self options:nil].lastObject;
    cell.learnModel = _datasArray[indexPath.row];
    
//    UIImageView *videoMarkView = [[UIImageView alloc] initWithFrame:CGRectMake(33, 23, 44, 44)];
    CGFloat itemWidth = 40;
    UIImageView *videoMarkView = [[UIImageView alloc] initWithFrame:CGRectMake((cell.titleImgView.frame.size.width*1.0-itemWidth)/2.0+8, (cell.titleImgView.frame.size.height*1.0-itemWidth)/2.0+15, itemWidth, itemWidth)];
    [videoMarkView setImage:[UIImage imageNamed:@"video_icon"]];
    videoMarkView.tag = 1020;
    
    if ([cell.learnModel.type isEqualToString:@"1"]) {
        [cell.contentView addSubview:videoMarkView];
    }

    return cell;
}

//将cell的高度固定为120
/*
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 90;
}
*/

//进入新闻的详情界面只需要传itemid的值即可
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    LearnModel *selModel = _datasArray[indexPath.row];
    if ([selModel.type isEqualToString:@"0"])
    {
        BookDetailVC *detailVC = [[BookDetailVC alloc] init];
        detailVC.bookID = selModel.itemid;
        detailVC.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:detailVC animated:YES];
    }
    else if([selModel.type isEqualToString:@"1"] || [selModel.type isEqualToString:@"2"])
    {
        MediaDetailVC *detailVC = [[MediaDetailVC alloc] init];
        detailVC.mediaID = selModel.itemid;
        detailVC.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:detailVC animated:YES];
    }
}

//加载数据
/*刷新or加载更多函数
 *@new
 *yes:刷新
 *no:加载更多
 */
- (void)reloadDataToNew:(BOOL)new
{
    NSMutableDictionary *CheckParams = [NSMutableDictionary dictionaryWithCapacity:5];
    
    NSString *typeStr = [NSString stringWithFormat:@"%d", _lawType];
    
    NSUInteger page = 1;
    if (!new)  // new = NO 设置page
    {
        page = _datasArray.count/pageSize + 1; //根据当前数据数组中的数据量来判断应该加载第几页
    }
    
    NSString *pageStr = [NSString stringWithFormat:@"%lu", page];
    
    [CheckParams setObject:[Config getOwnUserID] forKey:@"userid"];
    [CheckParams setObject:typeStr forKey:@"type"];
    [CheckParams setObject:pageStr forKey:@"page"];
    [CheckParams setObject:@"6" forKey:@"pagesize"];
    
    NSString *resultSign = [NSString getSignFromParam:CheckParams andSession:[Config getOwnSession]];
    [CheckParams setObject:resultSign forKey:@"sign"];
    [MyDataService requestURL:@"studylist.php" httpMethod:@"GET" params:CheckParams fileDatas:nil complection:^(id result) {
        NSString *response = [result objectForKey:@"response"];
        if ([response isEqualToString:@"studylist"]) {
            NSDictionary *newslistDic = result[@"studylist"];
            NSArray *newsList = newslistDic[@"list"];
            NSInteger totalCount = [newslistDic[@"totalcount"] integerValue];
            
            /*
             *思路：判断是否是刷新
             *是：移除dataArray中的数据，重新加载第一页
             *否：加载下一页的数据，并且拼接到已存在的数据数组中
             */
            if (new) {
                if (_datasArray.count != 0) {
                    [_datasArray removeAllObjects]; //刷新时，将已有数据清除，加载最新数据
                }
            }
            if (totalCount == _datasArray.count) {
                MBProgressHUD *hud = [Config createHUD];
                hud.mode = MBProgressHUDModeCustomView;
                hud.customView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"done"]];
                hud.labelText = @"没有更多数据";
                [hud hide:YES afterDelay:1];
                [self.tableView.legendFooter setState:MJRefreshFooterStateNoMoreData];
            }
            else
            {
                for(NSDictionary *dataDic in newsList)
                {
//                    LearnModel *newModel = [[LearnModel alloc] initWithDataDic:dataDic];
                    LearnModel *newModel = [LearnModel yy_modelWithJSON:dataDic];
                    newModel.modelType = LearnModelTypeAuOrSpeaker;
                    [_datasArray addObject:newModel];
                }
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self.tableView.legendHeader endRefreshing];
                    [self.tableView.legendFooter endRefreshing];
                    [self.tableView reloadData];
                });
            }
        }
        
        if ([response isEqualToString:@"error"]) {
            NSDictionary *errorDic = [result objectForKey:@"error"];
            NSString *text = errorDic[@"text"];
            MBProgressHUD *hud = [Config createHUD];
            hud.mode = MBProgressHUDModeCustomView;
            
            hud.customView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"error"]];
            hud.labelText = text;
            [hud hide:YES afterDelay:1];
        }
        
    } failureAction:^{
        //        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:@"新闻数据获取错误" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        //        [alertView show];
        MBProgressHUD *hud = [Config createHUD];
        hud.mode = MBProgressHUDModeCustomView;
        hud.customView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"error"]];
        hud.labelText = @"数据错误";
        [hud hide:YES afterDelay:1];
        [self.tableView.legendHeader endRefreshing];
        [self.tableView.legendFooter endRefreshing];
    }];
}

- (void)createHeaderView
{
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 80)];
    headerView.backgroundColor = [UIColor colorWithHexString:UIBgColorValue];
    LBBtnModel *bookModel = [[LBBtnModel alloc] initWithImgName:@"child_book_icon" labelTitle:@"书籍" btnType:LBBtnTypeRegular];
    LBBtnModel *videoModel = [[LBBtnModel alloc] initWithImgName:@"child_video_icon" labelTitle:@"视频" btnType:LBBtnTypeRegular];
    LBBtnModel *vioceModel = [[LBBtnModel alloc] initWithImgName:@"child_vioce_icon" labelTitle:@"录音" btnType:LBBtnTypeRegular];

//    NSArray *btnImgs = @[@"lawMaterial01", @"lawMaterial02", @"lawMaterial03"];
    NSArray *btnModelArray = @[bookModel, videoModel, vioceModel];
    CGFloat btnWidth = 80;
    CGFloat blockWidth = (kScreenWidth-btnWidth*3)/3;
    for (int i = 0; i < 3; i++) {
        /*
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.frame = CGRectMake(blockWidth/2+(btnWidth+blockWidth)*i, 10, btnWidth, btnWidth);
        [button setImage:[UIImage imageNamed:btnImgs[i]] forState:UIControlStateNormal];
        button.tag = 100+i;
        [button addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
        [headerView addSubview:button];
         */
        LBBtnModel *thisModel = btnModelArray[i];
        ChildLearnBtn *button = [ChildLearnBtn buttonWithType:UIButtonTypeCustom];
        button.btnModel = thisModel;
        button.frame = CGRectMake(blockWidth/2+(btnWidth+blockWidth)*i, 10, btnWidth, btnWidth);
        button.tag = 100 + i;
        [button addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
        [headerView addSubview:button];
    }
    self.tableView.tableHeaderView = headerView;
}

- (void)buttonAction:(UIButton *)button
{
    [_childSwipableVC scrollToViewAtIndex:button.tag - 100];
    _childSwipableVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:_childSwipableVC animated:YES];
}

@end
